<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { series, xAxis, yAxis, tooltip, windowResize } from '@/views/common'
import { ECharts } from 'echarts'
import * as echarts from 'echarts'
import { chunk, uniq } from 'lodash'
import { Swiper, SwiperSlide } from 'swiper/vue/swiper-vue'
import moment from 'moment'
import { getDictionary } from '@/views/science/api/technologyawards'
import { isSuccess } from '@/views/cockpit/common'
import {
  jfOutPutRequest,
  jfOutRequest,
  jfPieRequest,
  jfRatioRequest,
  jfTypeRequest,
  jfInputRequest,
} from '@/views/cockpit/projectSection/api'
// import {Autoplay} from "swiper";
import { useRouter } from 'vue-router'
import { fontSizeRem } from '@/utils/utils'
enum loopKey {
  money = 'num',
  name = 'contractName',
  time = 'time',
}
type LoopData = {
  [key in Exclude<loopKey, loopKey.money>]: string
} & {
  [loopKey.money]: number
}
const router = useRouter()
const isCompany = router.currentRoute.value.path === '/cockpit/xmSection/companyFunding'
const yearValue = ref<string>(moment().format('YYYY'))
const level = ref<string>('')
const type = ref<string>('')
const levelOptions = ref<Record<string, string>[]>([])
const typeOptions = ref<Record<string, string>[]>([])
const initOptions = () => {
  getDictionary(['XMZX_LEVEL_TYPE']).then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || {}
      levelOptions.value = data.XMZX_LEVEL_TYPE || []
    }
  })
}
const lineBar = ref<HTMLDivElement>()
const pie = ref<HTMLDivElement>()
const bar = ref<HTMLDivElement>()
let lineBarChart: ECharts
let pieChart: ECharts
let barChart: ECharts
const levelChange = () => {
  const options = (levelOptions.value.find((t) => t.itemValue === level.value)?.children ||
    []) as Record<string, string>[]
  type.value = ''
  typeOptions.value = options
  initChart()
}

const inputTotal = ref<number>(0)
const outputTotal = ref<number>(0)
const initChart = () => {
  // 科研投入
  jfOutRequest(yearValue.value, level.value, type.value).then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || []
      const lineX = data.map((t) => t.time) || []
      const lineY = data.map((t) => t.num1) || []
      const lineY2 = data.map((t) => t.num2) || []
      // 柱状线性图
      if (lineBarChart) lineBarChart.dispose()
      lineBarChart = echarts.init(lineBar.value)
      lineBarChart.setOption({
        tooltip,
        grid: {
          top: '50',
          left: '30',
          right: '30',
          bottom: '0',
          containLabel: true,
        },
        legend: {
          textStyle: {
            color: '#fff',
          },
          right: '20%',
        },
        xAxis: {
          axisPointer: {
            type: 'shadow',
          },
          ...xAxis(lineX, false),
          // axisLine: {
          //   show: true,
          // },
        },
        yAxis: [
          {
            name: '单位 (万元)',
            ...yAxis(false),
          },
          {
            name: '项目 (个)',
            ...yAxis(false),
            position: 'right',
          },
        ],
        series: [
          {
            ...series(lineY, '#4272DF', '项目数', '个'),
            barWidth: fontSizeRem(0.3),
            label: {
              show: true,
              position:'top',
            },
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr = params.value > 0 ? ['#4272DF', '#08103B'] : ['#08103B', '#4272DF']
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
          },
          {
            ...series(lineY2, '#A53976', '投入金额', '万元', 'line'),
            smooth: true,
            yAxisIndex: 1,
            label: {
              show: true,
              position:'top',
            },
          },
        ],
      })
    } else if (lineBarChart) lineBarChart.dispose()
  })
  // 收支对比
  jfRatioRequest(yearValue.value, level.value, type.value).then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || []
      const lineX: string[] = uniq(data.map((t) => t.time) || [])
      const input: number[] = data.filter((t) => t.costCategory === 1).map((t) => t.num) || []
      const output: number[] = data.filter((t) => t.costCategory === 2).map((t) => t.num) || []
      inputTotal.value = input.reduce((now, next) => now + next, 0)
      outputTotal.value = output.reduce((now, next) => now + next, 0)
      if (barChart) barChart.dispose()
      barChart = echarts.init(bar.value)
      barChart.setOption({
        tooltip,
        // title:{
        //   text:'asdasd'
        // },
        grid: {
          top: '50',
          left: '30',
          right: '30',
          bottom: '0',
          containLabel: true,
        },
        legend: {
          itemWidth: 14,
          textStyle: {
            color: '#fff',
          },
          left: '20%',
        },
        xAxis: {
          axisPointer: {
            type: 'shadow',
          },
          ...xAxis(lineX, false),
        },
        yAxis: [
          {
            name: '收入',
            ...yAxis(false),
          },
          {
            name: '支出',
            ...yAxis(false),
            position: 'right',
          },
        ],
        color: ['#5470C6', '#A53976'],
        series: [
          {
            ...series(input, '#5470C6', '收入', '万元'),
            barWidth: fontSizeRem(0.3),
            label: {
              show: true,
              position:'top'
            },
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr = params.value > 0 ? ['#5470C6', '#08103B'] : ['#08103B', '#5470C6']
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
          },
          {
            ...series(output, '#A53976', '支出', '万元'),
            yAxisIndex: 1,
            barWidth: fontSizeRem(0.3),
            label: {
              show: true,
              position:'top'
            },
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr = params.value > 0 ? ['#A53976', '#08103B'] : ['#08103B', '#A53976']
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
          },
        ],
      })
    } else {
      inputTotal.value = 0
      outputTotal.value = 0
      if (barChart) barChart.dispose()
    }
  })
  const initPie = (pieData: Record<string, any>) => {
    if (pieChart) pieChart.dispose()
    pieChart = echarts.init(pie.value)
    pieChart.setOption({
      tooltip: {
        trigger: 'item',
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: '0',
        left: '65%',
        width: '1',
        top: 'center',
        textStyle: {
          color: '#C8CBDB',
        },
        pageIconColor: '#ff781f', //翻页箭头颜色
        pageTextStyle: {
          color: '#C8CBDB', //翻页数字颜色
        },
      },
      series: [
        {
          name: '分子公司项目占比',
          type: 'pie',
          radius: '66%',
          center: ['30%', '50%'],
          data: pieData,
          label: {
            show: true,
            formatter: '{b}：{d}%',
            color: '#C8CBDB',
            width: 120,
            overflow:'break',
          },
        },
      ],
    })
  }
  if (isCompany) {
    // 支出品类占比
    jfTypeRequest(yearValue.value, level.value, type.value).then((res) => {
      if (isSuccess(res)) {
        const data = res.data.data || []
        const pieData = data.map((t) => ({ value: t.num || 0, name: t.subjectName || '' })) || []
        initPie(pieData)
      } else if (pieChart) pieChart.dispose()
    })
  } else {
    // 分子公司项目占比
    jfPieRequest(yearValue.value, level.value, type.value).then((res) => {
      if (isSuccess(res)) {
        const data = res.data.data || []
        const pieData =
          data.map((t) => ({ value: t.num || 0, name: t.internalUnitName || '' })) || []
        initPie(pieData)
      } else if (pieChart) pieChart.dispose()
    })
  }
}
const windowEvent = () => {
  windowResize(300, () => {
    if (lineBarChart) lineBarChart.resize()
    if (pieChart) pieChart.resize()
    if (barChart) barChart.resize()
  })
}
const lineHeight: number = 50
const loopYear = ref<string>(moment().format('YYYY'))
const loopResult = ref<LoopData[][]>([])
const getLoopData = () => {
  loopResult.value = []
  const initLoop = (data: LoopData[]) => {
    const el: Element = document.getElementsByClassName('swiperContent')[0]
    let height: number = 0
    let chunkNum: number = 0
    if (el) {
      height = el.clientHeight
      chunkNum = Math.floor(height / lineHeight)
    }
    loopResult.value = chunk(data, chunkNum)
  }
  if (isCompany) {
    jfInputRequest(loopYear.value).then((res) => {
      if (isSuccess(res)) {
        const data = (res.data.data || []) as LoopData[]
        initLoop(data)
      }
    })
  } else {
    jfOutPutRequest(loopYear.value).then((res) => {
      if (isSuccess(res)) {
        const data = (res.data.data || []) as LoopData[]
        initLoop(data)
      }
    })
  }
}
onMounted(() => {
  initOptions()
  initChart()
  getLoopData()
  window.addEventListener('resize', () => {
    windowEvent()
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', windowEvent)
})
</script>

<template>
  <div class="chartContent">
    <div class="search mb10" style="display: flex">
      <div class="mr20">
        <el-date-picker
          v-model="yearValue"
          type="year"
          placeholder="选择年度"
          value-format="YYYY"
          format="YYYY"
          clearable
          @change="initChart"
        />
      </div>
      <el-select
        v-model="level"
        clearable
        class="mr20"
        placeholder="项目等级"
        @change="levelChange"
      >
        <el-option
          v-for="item in levelOptions"
          :key="item.itemValue"
          :label="item.itemText"
          :value="item.itemValue"
        />
      </el-select>
      <el-select v-model="type" clearable class="m-2" placeholder="项目类型" @change="initChart">
        <el-option
          v-for="item in typeOptions"
          :key="item.itemValue"
          :label="item.itemText"
          :value="item.itemValue"
        />
      </el-select>
    </div>
    <div class="content">
      <div class="finance mb20">
        <div class="modal mr20">
          <span class="modalTitle">科研投入</span>
          <div ref="lineBar" class="chat"></div>
        </div>
        <div class="modal modal1">
          <span class="modalTitle">{{ isCompany ? '支出品类占比' : '分子公司项目占比' }}</span>
          <div ref="pie" class="chat"></div>
        </div>
      </div>
      <div class="finance output">
        <div class="modal mr20 pt60">
          <span class="modalTitle">收支对比</span>
          <div class="money">
            <div class="tip">
              <span class="desc">年支出总额</span>
              <div class="desc">
                <span class="num">{{ outputTotal }}</span> 万元
              </div>
            </div>
            <div class="tip">
              <span class="desc">年收入总额</span>
              <div class="desc">
                <span class="num">{{ inputTotal }}</span> 万元
              </div>
            </div>
          </div>
          <div ref="bar" class="chat"></div>
        </div>
        <div class="modal modal1 pt45">
          <div class="searchItem searchRight">
            <el-date-picker
              v-model="loopYear"
              type="year"
              placeholder="选择年度"
              value-format="YYYY"
              format="YYYY"
              clearable
              @change="getLoopData"
            />
          </div>
          <div class="modalTitle">
            {{ isCompany ? '经费收入明细' : '经费支出明细' }}
          </div>
          <div class="rankContent">
            <div class="rankLi head">
              <div class="item">
                <div class="td"><span class="txt">计划完成日期</span></div>
                <div class="td"><span class="txt">合同名称</span></div>
                <div class="td"><span class="txt">金额 (万)</span></div>
              </div>
            </div>
            <!-- :modules="[Autoplay]"
                  :autoplay="{delay: 6000, disableOnInteraction: false}" loop-->
            <swiper class="swiperContent" direction="vertical">
              <swiper-slide v-for="(slide, index) in loopResult" :key="index + 'slide'">
                <div class="rankLi body">
                  <div class="item" v-for="(option, idx) in slide" :key="index + 'slide' + idx">
                    <div class="td">
                      <span class="txt">{{ option.time }}</span>
                    </div>
                    <div class="td" :title="option.contractName || ''">
                      <span class="txt">{{ option.contractName }}</span>
                    </div>
                    <div class="td">
                      <span class="txt">{{ option.num }}</span>
                    </div>
                  </div>
                </div>
              </swiper-slide>
            </swiper>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/css/theme';
@import '../../common';
.chartContent {
  display: flex;
  flex-direction: column;
  background-color: $primary-back;
  .search {
    max-height: 32px;
  }
  .content {
    display: flex;
    flex: 1 1 0;
    flex-direction: column;
    .finance {
      display: flex;
      justify-content: space-between;
      flex: 1 1 0;
      align-items: center;
      .modal {
        position: relative;
        display: flex;
        padding: 5vh 3vh;
        width: 57%;
        height: 100%;
        background-image: url(../../img/modal1.png);
        background-size: 100% 100%;
        // border: 1px solid $primary-color;
        &:first-child {
          width: 43%;
        }
        .money {
          position: absolute;
          top: 3vh;
          // right: 0;
          left:50%;
          // transform: translateX(-50%);
          display: flex;
          z-index: 1;
          .tip {
            display: flex;
            flex-direction: column;
            padding: 5px 20px;
            font-size: 14px;
            border-radius: 10px;
            background-color: #192e6e;
            color: #fff;
            &:first-child {
              margin-right: 10px;
            }
            .desc {
              &:first-child {
                margin-bottom: 5px;
              }
              .num {
                color: $primary-warn;
              }
            }
          }
        }
        .titleYear {
          position: absolute;
          top: 6.5px;
          left: 10px;
          z-index: 2;
          max-width: 150px;
        }
        .rankContent {
          width: 100%;
          margin-top: 2vh;
          padding: 10px 0 0 0;
          .rankLi {
            &.head {
              max-height: 30px;
              .item {
                height: 30px;
                line-height: 30px;
                min-height: 30px;
              }
            }
            .item {
              height: 30px;
              line-height: 30px;
              font-size: 14px;
              .td {
                width: 33%;
                min-width: 33%;
                max-width: 33%;
              }
            }
          }
        }
      }
      .modal1 {
        background-image: url(../../img/modal1.png);
        background-size: 100% 100%;
      }
    }
  }
}
</style>
